package com.caishi.lkx.utils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Base64;
import java.io.InputStream;


// 平台证书验签工具类
public class WechatPaySignatureVerifier {

    // 加载平台证书（从资源文件中加载）
    public static PublicKey loadWechatPayPublicKey(String certPath) throws Exception {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        try (InputStream inputStream = WechatPaySignatureVerifier.class.getClassLoader().getResourceAsStream(certPath)) {
            X509Certificate certificate = (X509Certificate) certificateFactory.generateCertificate(inputStream);
            return certificate.getPublicKey();
        }
    }

    // 验证签名
    public static boolean verifySignature(String message, String signatureStr, PublicKey publicKey) throws Exception {
        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initVerify(publicKey);
        signature.update(message.getBytes(StandardCharsets.UTF_8));
        byte[] signatureBytes = Base64.getDecoder().decode(signatureStr);
        return signature.verify(signatureBytes);
    }

//    public static void main(String[] args) throws Exception {
//        // 示例数据：请替换为实际接收到的数据
//        String notifyId = "some_notify_id";       // 微信支付异步通知 ID（来自 HTTP 头 Wechatpay-Nonce）
//        String timestamp = "1723123456";         // 时间戳
//        String nonce = "nonce_str";              // 随机串
//        String body = "{\"resource_type\":\"encrypt-resource\"}";  // 回调内容
//
//        // 拼接待签名字符串
//        String message = timestamp + "\n" + nonce + "\n" + body + "\n";
//
//        // 加载公钥（路径需根据你的资源结构调整）
//        PublicKey publicKey = loadWechatPayPublicKey("/cert/platform.pem");
//
//        // 获取到的签名值（来自 HTTP 头 Wechatpay-Signature）
//        String signature = "base64_encoded_signature_value";
//
//        // 执行验签
//        boolean isValid = verifySignature(message, signature, publicKey);
//        System.out.println("签名是否有效: " + isValid);
//    }
}

